<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名" prop="customerName">
        <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售员名" prop="createName" label-width="100px">
        <el-input
            v-model="queryParams.createName"
            placeholder="请输入销售员名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable style="width: 200px">
          <el-option
              v-for="dict in sale_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['sale:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['sale:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['sale:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['sale:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="销售订单号" align="center" prop="orderNo" width="130"/>
      <el-table-column label="客户" align="center" prop="customerName" width="150" show-overflow-tooltip/>
      <el-table-column label="销售员" align="center" prop="createName"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="合计数量" align="center" prop="number"/>
      <el-table-column label="最终合计价格,单位:元" align="center" prop="totalPrice" width="120"/>
      <el-table-column label="合计产品价格,单位:元" align="center" prop="totalProductPrice" width="120"/>
      <el-table-column label="已收款金额,单位:元" align="center" prop="receiptPrice" width="120"/>
      <el-table-column label="优惠率,百分比" align="center" prop="discountPercent" width="110"/>
      <el-table-column label="优惠金额,单位:元" align="center" prop="discountPrice" width="130"/>
      <el-table-column label="其它金额,单位:元" align="center" prop="otherPrice" width="130"/>
      <el-table-column label="备注" align="center" prop="remark" width="100"/>
      <el-table-column label="修改人" align="center" prop="updateName"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="产品销售状态" prop="status" width="80" fixed="right">
        <template #default="scope">
          <dict-tag
              :options="sale_order_status" :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Position" @click="updateStatus1(scope.row)">发布</el-button>
          <el-button link type="primary" icon="Select" @click="updateStatus2(scope.row)">审批</el-button>

          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sale:order:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['sale:order:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改销售订单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="订单号" prop="orderNo" >
      <!--根据选择的row数据显示订单号-->
              <el-input v-model="xsdd" disabled style="width: 230px"/>
        </el-form-item>
        <el-form-item label="客户" >

              <el-select v-model="form.customerId" placeholder="选择客户" style="width: 220px" >
                <el-option
                    v-for="item in customers"
                    :key="item.customerName"
                    :label="item.customerName"
                    :value="item.customerId"
                    @click="change(item)"
                />
              </el-select>

        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable
                          v-model="form.createTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="销售产品" >

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAddTGoods">添加</el-button>
            </el-col>
          </el-row>
          <el-table :data="goodsList"  ref="tGoods" >
            <el-table-column label="产品名字" prop="goodName" width="150">
              <template #default="scope">
                <el-select v-model="scope.row.productId"  @change="updatePrice(scope.row)" placeholder="选择产品" style="width: 120px">
                  <el-option
                      v-for="item in options"
                      :key="item.productName"
                      :label="item.productName"
                      :value="item.productId"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="单价" prop="price" width="150">
              <template #default="scope">
                <el-input  disabled :value="scope.row.price" placeholder="请输入单价" />
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="number" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.number" placeholder="请输入数量" />
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="number" width="150">
              <template #default="scope">
                <el-button type="danger" icon="Delete"  @click="handleDeleteTGoods(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>


        </el-form-item>
        <el-form-item label="产品总数量" prop="number">
          <el-input v-model="form.number" disabled />
        </el-form-item>

        <el-form-item label="最终合计价格,单位:元" prop="totalPrice">
          <el-input v-model="form.totalPrice" disabled />
        </el-form-item>

        <el-form-item label="合计产品价格,单位:元" prop="totalProductPrice">
          <el-input v-model="form.totalProductPrice" disabled/>
        </el-form-item>
        <el-form-item label="优惠率,百分比" prop="discountPercent">
          <el-input v-model="form.discountPercent" placeholder="请输入优惠率,百分比"/>
        </el-form-item>
        <el-form-item label="优惠金额,单位:元" prop="discountPrice">
          <el-input v-model="form.discountPrice" placeholder="请输入优惠金额,单位:元"/>
        </el-form-item>
        <el-form-item label="其它金额,单位:元" prop="otherPrice">
          <el-input v-model="form.otherPrice" placeholder="请输入其它金额,单位:元"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">

import {updateStatus} from "../../../api/sale/order.js";

function change(item){
  form.value.customerName = item.customerName
}


import {listOrder, getOrder, delOrder, addOrder, updateOrder, getXSDD} from "@/api/sale/order";
import  {listProduct} from "@/api/base/product";
import {getCustomer, listCustomer} from "../../../api/base/customer.js";
import { ref, watch } from 'vue'
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const {sys_normal_disable, sale_order_status} = proxy.useDict("sys_normal_disable", "sale_order_status");

const goodsList = ref([])
const options =ref([])
let customers = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    customerId: null,
    saleUserId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    number: null,
    totalPrice: null,
    totalProductPrice: null,
    receiptPrice: null,
    discountPercent: null,
    discountPrice: null,
    otherPrice: null,
    deleted: null,
    customerName: null,
    contactPerson: null,
    createName: null,
    updateName: null,
    orderNo: null
  },
  rules: {
    status: [
      {required: true, message: "销售状态不能为空", trigger: "change"}
    ],
    customerId: [
      {required: true, message: "客户 id不能为空", trigger: "blur"}
    ],
    saleUserId: [
      {required: true, message: "销售员 id不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "下单时间不能为空", trigger: "blur"}
    ],
    // totalPrice: [
    //   { required: true, message: "最终合计价格,单位:元不能为空", trigger: "blur" }
    // ],
    // totalProductPrice: [
    //   { required: true, message: "合计产品价格,单位:元不能为空", trigger: "blur" }
    // ],
    // receiptPrice: [
    //   { required: true, message: "已收款金额,单位:元不能为空", trigger: "blur" }
    // ],
    // discountPercent: [
    //   { required: true, message: "优惠率,百分比不能为空", trigger: "blur" }
    // ],
    // discountPrice: [
    //   { required: true, message: "优惠金额,单位:元不能为空", trigger: "blur" }
    // ]
  }
});


const {queryParams, form, rules} = toRefs(data);

function updateStatus2(row){
  console.log(row.status)
  if (row.status !== 2 && row.status !== 1) {
    if (row.status === 0) {
        ElMessage.warning('该订单未发布，请先发布')
      return;
    }
    ElMessage.warning('该订单已审批请不要重复审批')
    return ;
  }
  updateStatus({id:row.id, status: 3})
  ElMessage.success('审批完成')
  setTimeout(() => {
    location.reload()
  },1500)

}

function updateStatus1(row){
  console.log(row.status)
  if (row.status !== 0) {
    ElMessage.warning('该订单已提交请不要重复提交')
    return ;
  }

  updateStatus({id:row.id, status: 1})
  ElMessage.success('提交成功')
  setTimeout(() => {
    location.reload()
  },1500)

}

// 增加计算逻辑，用于自动计算最终合计价格和合计产品价格

watch([form,goodsList],()=>{
  calculateTotals()
},{deep:true})

function calculateTotals() {
  // 计算合计产品价格
  form.value.totalProductPrice = goodsList.value.reduce((sum, item) => {
    return sum + (item.price || 0) * (item.number || 0);
  }, 0);

  //计算总数量
  form.value.number = goodsList.value.reduce((sum, item) => {
    return sum + (parseInt(item.number) || 0);
  }, 0);

  // 计算最终合计价格
  const totalProductPrice = parseFloat(form.value.totalProductPrice) || 0;
  const discountPercent = parseFloat(form.value.discountPercent) || 0;
  const discountPrice = parseFloat(form.value.discountPrice) || 0;
  const otherPrice = parseFloat(form.value.otherPrice) || 0;

  form.value.totalPrice =  totalProductPrice + otherPrice - discountPrice - (totalProductPrice * (discountPercent / 100));
}

function updatePrice(row) {
  
  //查找满足条件的值
  const selectedOption = this.options.find(
      (option) => option.productId === row.productId
  );
  if (selectedOption) {
    row.price = selectedOption.price;
  } else {
    row.price = null;
  }
}


function handleDeleteTGoods(index) {
  //删除当前行
  goodsList.value.splice(index, 1);

}

/** 添加按钮操作 */
function handleAddTGoods() {
  let obj = {};
  obj.goodName = "";
  obj.price = "";
  obj.number = "";

  goodsList.value.push(obj);
}

/** 查询销售订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

  listProduct().then(resp => {
    resp.rows.filter(p => {
      options.value.push({
        productId:p.id,
        productName:p.productName,
        price:p.price
      })
    })
  })

  listCustomer().then(resp =>{
    resp.rows.filter(c => {
      customers.value.push({
        customerName:c.customerName,
        customerId:c.id,
        contactPerson:c.contactPerson
      })
    })
  })

}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productId:null,
    orderNo: null,
    status: null,
    customerId: null,
    saleUserId: null,
    number: null,
    totalPrice: null,
    totalProductPrice: null,
    receiptPrice: null,
    discountPercent: null,
    discountPrice: null,
    otherPrice: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    customerName: null,
    contactPerson: null,
    createName: null,
    updateName: null
  };
  proxy.resetForm("orderRef");
}
//生成订单号
let xsdd = ref();

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  goodsList.value = [];
  getXSDD().then(resp =>{
    xsdd.value = resp.msg
  })
  reset();
  open.value = true;
  title.value = "添加销售订单";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  goodsList.value = [];
  // 检查选中数据是否存在不可修改的状态
  const invalidItems = ids.value.map(id => orderList.value.find(item => item.id === id)).filter(item => item.status !== 0);

  if (invalidItems.length > 0) {
    return proxy.$modal.msgError("存在已发布订单，无法修改");
  }

  // 当前行在修改时查询状态不为0时显示，该订单状态已发布无法修改
  let status1 = row.status;
  console.log(row)
  if (status1 != null) {
    if (status1 != 0) {
      return proxy.$modal.msgError("订单状态已发布无法修改");
    }
  }

  xsdd.value = row.orderNo
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;

    //遍历每一个订单商品对象
    form.value.goodsList.forEach((item1) => {

      //根据商品id查商品详情
      listProduct({id : item1.productId}).then(resp =>{
        resp.rows.forEach((item2) => {
          item1.goodName = item2.productName
          item1.price = item2.price
        })
      })
      goodsList.value.push(item1)

    })

    open.value = true;
    title.value = "修改销售订单";
  });

}

/** 提交按钮 */
function submitForm() {
  form.value.orderNo = xsdd.value
  form.value.goodsList = goodsList.value
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 检查选中数据是否存在不可删除的状态
  const invalidItems = ids.value.map(id => orderList.value.find(item => item.id === id)).filter(item => item.status !== 0);

  if (invalidItems.length > 0) {
    return proxy.$modal.msgError("存在已发布订单，无法删除");
  }

  // 当前行在删除时查询状态不为0时显示，该订单状态已发布无法删除
  let status1 = row.status;
  console.log(row)
  if (status1 != null) {
    if (status1 != 0) {
      return proxy.$modal.msgError("订单状态已发布无法删除");
    }
  }

  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sale/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
